package com.dailyblue.java.project.smbms.users.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dailyblue.java.spring.project.smbms.commons.bean.Users;
import com.dailyblue.java.spring.project.smbms.commons.config.JsonResult;
import com.dailyblue.java.spring.project.smbms.commons.config.JwtConfig;
import com.dailyblue.java.spring.project.smbms.commons.config.ResultCode;
import com.dailyblue.java.spring.project.smbms.commons.config.ResultTool;
import com.dailyblue.java.spring.project.smbms.commons.service.UsersService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UsersController {
    @Resource
    private UsersService usersService;

    @PostMapping("/login")
    public JsonResult<String> login(Users user) {
        return usersService.login(user);
    }

    @GetMapping("/a")
    public JsonResult<String> a(HttpServletRequest request) {
        boolean b = JwtConfig.checkToken(request);
        if (!b) {
            return ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        }
        return ResultTool.success("欢迎你的访问！");
    }

    @GetMapping("/find")
    public JsonResult<PageInfo<Users>> find(@RequestParam(name = "page", defaultValue = "1") int page) {
        return usersService.findAllUsers(page);
    }

    @GetMapping("/search")
    public JsonResult<PageInfo<Users>> find(@RequestParam(name = "page", defaultValue = "1") int page, String name, Integer role) {
        return usersService.findUserByNameAndRoleName(name, role, page);
    }

    @DeleteMapping("/delete")
    public void delete(int id, int page) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        usersService.delete(wrapper, page);
        JsonResult<PageInfo<Users>> json = find(1);
        int pages = json.getData().getPages();
        if (pages > page) {
            for (int i = page + 1; i <= pages; i++) {
                usersService.delete(i);
            }
        }
    }

    @PutMapping("/update")
    public void update(Users user) {
        usersService.saveOrUpdate(user);
    }

    @GetMapping("/id")
    public JsonResult<Users> findById(int id) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Users user = usersService.getOne(wrapper);
        JsonResult<Users> json = ResultTool.success(user);
        return json;
    }

    @PostMapping("/save")
    public void save(Users user) {
        usersService.save(user);
    }

}
